package de.ohmhochschule.bme;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * To test this you need to:
 * - run this in a real device (will not work in simulator)
 * - have the device run as a hotspot
 * - deploy and execute this app on the device
 * - open on the PC a command prompt/terminal window and enter:
 *   telnet 192.168.43.1 8080
 */
public class SocketServerActivity extends Activity {

	private TextView textView1;
	private Thread serverThread;
	private ServerSocket server;
	private int port = 8080;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i(getLocalClassName(), "started...");
		setContentView(R.layout.main);
		String sIP = "";
		try {
			Socket socket = new Socket("www.google.com", 80);
			sIP = socket.getLocalAddress().toString();
			Log.i("", socket.getLocalAddress().toString());
			socket.close();
		} catch (Exception e) {
			Log.i("", e.getMessage());
		}

		textView1 = (TextView) findViewById(R.id.textView1);
		textView1.setText("Server running on: " + getLocalIpAddress() + ":"
				+ port);

		serverThread = new Thread(new ServerThread());
		serverThread.start();
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.i(getLocalClassName(), "onStop()");
		serverThread.stop();	// not very nice
		try {
			Thread.sleep(500);	// wait a little
		} catch (InterruptedException e1) {}
		try {
			server.close();
		} catch (IOException e) {
			Log.e(getLocalClassName(), e.getMessage());
		}
	}

	public String getLocalIpAddress() {
		// dirty trick to get current local IP:
		// Socket socket = new Socket("www.google.com", 80);
		// sIP = socket.getLocalAddress().toString();
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException e) {
			Log.e(getLocalClassName(), e.getMessage());
		}
		return null;
	}

	class ServerThread implements Runnable {
		public void run() {
			try {
				server = new ServerSocket(port);
				while (true) {
					Socket socket = server.accept();
					try {
						OutputStream out = socket.getOutputStream();
						out.write("Hi there from SocketServerActivity!".getBytes());
						out.flush();
						out.close();
					} catch (Exception e) {
						Log.e(getLocalClassName(), e.getMessage());
					}
					socket.close();
				}

			} catch (Exception e) {
				Log.e(getLocalClassName(), e.getMessage());
			}
		}
	}
}
